<template>
  <!---搜索表单-->
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="6">
          <el-form-item label="优惠卷类型" class="el_form_item_style">
            <el-cascader :options="options" clearable></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="优惠卷状态" class="el_form_item_style">
            <el-cascader :options="options" clearable></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="优惠卷名称" class="el_form_item_style">
            <el-input
              v-model="queryDto.name"
              style="width: 100%"
              placeholder="活动名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item class="el_form_item_style">
            <el-button type="primary" size="small" @click="searchActivity">
              搜索
            </el-button>
            <el-button size="small" @click="resetData">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>

  <!--添加按钮-->
  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow">添 加</el-button>
  </div>

  <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
    <el-form label-width="120px">
      <el-form-item label="优惠卷名称">
        <el-input v-model="couponAddDto.name" />
      </el-form-item>
      <el-form-item label="使用范围">
        <el-radio v-model="couponAddDto.specific" :label="false">不限定</el-radio>
        <el-radio v-model="couponAddDto.specific" :label="true">指定商品分类</el-radio>
      </el-form-item>
      <el-form-item v-if="couponAddDto.specific">
        <SelectCategory @handle-change="handleChange" />
      </el-form-item>
      <el-form-item label="优惠卷类型">
        <el-radio v-model="couponAddDto.discountType" label="每满减">每满减</el-radio>
        <el-radio v-model="couponAddDto.discountType" label="满减">满减</el-radio>
        <el-radio v-model="couponAddDto.discountType" label="折扣">折扣</el-radio>
        <el-radio v-model="couponAddDto.discountType" label="无门槛">无门槛</el-radio>
      </el-form-item>
      <el-form-item v-if="couponAddDto.discountType==='每满减'">
        每满
        <el-input maxlength="10" style="width: 80px;margin: 0 5px" v-model.number="couponAddDto.thresholdAmount" />
        元，减
        <el-input maxlength="10" style="width: 80px;margin: 0 5px" v-model.number="couponAddDto.discountValue" />
        元，最高减
        <el-input maxlength="10" style="width: 80px;margin: 0 5px" v-model.number="couponAddDto.maxDiscountAmount" />
        元
      </el-form-item>
      <el-form-item v-if="couponAddDto.discountType==='满减'">
        满
        <el-input style="width: 80px;margin: 0 5px" v-model="couponAddDto.thresholdAmount" />
        元，
        减
        <el-input style="width: 80px;margin: 0 5px" v-model="couponAddDto.discountValue" />
        元
      </el-form-item>
      <el-form-item v-if="couponAddDto.discountType==='折扣'">
        打
        <el-input style="width: 80px;margin: 0 5px" v-model="couponAddDto.discountValue" />
        折
      </el-form-item>
      <el-form-item label="推广方式">
        <el-radio v-model="couponAddDto.obtainWay" label="手动领取">手动领取</el-radio>
        <el-radio v-model="couponAddDto.obtainWay" label="指定发放">指定发放</el-radio>
      </el-form-item>
      <el-form-item label="发放数量">
        <el-input style="width: 80px;margin: 0 5px" v-model="couponAddDto.totalNum" />
        张
      </el-form-item>
      <el-form-item label="每人限领">
        <el-input style="width: 80px;margin: 0 5px" v-model="couponAddDto.userLimit" />
        张
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!---数据表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column prop="id" label="序号" width="200px" />
    <el-table-column prop="name" label="优惠卷名称" width="100px" />
    <el-table-column label="优惠卷规则" #default="scope" width="300px">
      <div v-if="scope.row.discountType==='每满减'">
        {{ "每满" + scope.row.thresholdAmount / 100 + "减" + scope.row.discountValue / 100 + "元，最高优惠金额:" + scope.row.maxDiscountAmount / 100 + "元" }}
      </div>
      <div v-if="scope.row.discountType==='满减'">
        {{ "满" + scope.row.thresholdAmount / 100 + "减" + scope.row.discountValue / 100 + "元" }}
      </div>
      <div v-if="scope.row.discountType==='折扣'">
        {{ "满" + scope.row.thresholdAmount / 100 + "元，打" + scope.row.discountValue / 100 + "折，最高优惠金额:" + scope.row.maxDiscountAmount / 100 + "元" }}
      </div>
    </el-table-column>
    <el-table-column label="使用范围" #default="scope" width="200px">
      {{ scope.row.specific === true ? "指定范围" : "全部商品分类" }}
    </el-table-column>
    <el-table-column label="推广方式" #default="scope" width="200px">
      <div v-if="scope.row.obtainWay==='手动领取'">
        {{ scope.row.obtainWay }}
      </div>
      <div v-if="scope.row.obtainWay==='指定发放'">
        {{ scope.row.obtainWay }}
      </div>
    </el-table-column>
    <el-table-column label="使用/领取/发放" #default="scope" width="200px">
      {{ scope.row.usedNum + "/" + scope.row.issueNum + "/" + scope.row.totalNum }}
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" width="200px" />
    <el-table-column prop="createTime" label="领用期限" #default="scope" width="200px">
      <div>
        {{ scope.row.issueBeginTime }}
      </div>
      <div>
        {{ scope.row.issueEndTime }}
      </div>
    </el-table-column>
    <el-table-column prop="createTime" label="使用期限" #default="scope" width="200px">
      {{ "领卷起" + scope.row.termDays + "天有效" }}
    </el-table-column>
    <el-table-column prop="status" label="状态" />
    <el-table-column label="操作" align="center" width="300" #default="scope" fixed="right">
      <el-button type="primary" size="small" @click="editSysUser(scope.row)">
        编辑
      </el-button>
      <el-button type="success" size="small" @click="grant(scope.row)">
        发放
      </el-button>
      <el-button type="warning" size="small" @click="showAssignRole(scope.row)">
        查看兑换码
      </el-button>
      <el-button type="danger" size="small" @click="showAssignRole(scope.row)">
        删除
      </el-button>
    </el-table-column>
  </el-table>

  <!-- 发放优惠卷 -->
  <el-dialog v-model="grantCoupon" title="设置领用/使用期限" width="40%">
    <el-form label-width="120px">
      <el-form-item label="发放方式">
        <!--    1:立刻发放,2: 定时发放   -->
        <el-radio v-model="grantData.way" :label="1">立刻发放</el-radio>
        <el-radio v-model="grantData.way" :label="2">定时发放</el-radio>
      </el-form-item>
      <el-form-item label="领用期限">
        <div v-if="grantData.way === 1">
          <el-date-picker
            v-model="grantCouponData.issueEndTime"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          >
          </el-date-picker>
        </div>
        <div v-if="grantData.way === 2">
          <el-date-picker
            v-model="grantData.issueTime"
            type="datetimerange"
            range-separator="To"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
      </el-form-item>
      <el-form-item label="使用期限方式">
        <el-radio v-model="grantData.usagePeriod" :label="1">固定天数</el-radio>
        <el-radio v-model="grantData.usagePeriod" :label="2">固定时间段</el-radio>
      </el-form-item>
      <el-form-item label="使用期限">
        <div v-if="grantData.usagePeriod === 1">
          <el-input maxlength="10" style="width: 80px;margin: 0 5px" v-model.number="grantCouponData.termDays" />
          天
        </div>
        <div v-if="grantData.usagePeriod === 2">
          <el-date-picker
            v-model="grantData.termTime"
            type="datetimerange"
            range-separator="To"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitGrantCoupon">提交</el-button>
        <el-button @click="grantCoupon = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-pagination
    v-model:current-page="queryDto.pageNum"
    v-model:page-size="queryDto.pageSize"
    :page-sizes="[10, 20, 50, 100]"
    @size-change="fetchData"
    @current-change="fetchData"
    layout="total, sizes, prev, pager, next"
    :total="total"
  />
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import { SaveCoupon, SelectCouponPage, IsCoupon } from "@/api/activity/coupon";
import SelectCategory from "@/components/SelectCategory/selectCategory.vue";

//判断时间段赋值给提交表单数据
const timeFormSubmit = (issueTime, termTime) => {
  if (issueTime != null && issueTime !== "") {
    grantCouponData.value.issueBeginTime = issueTime[0];
    grantCouponData.value.issueEndTime = issueTime[1];
  }
  if (termTime != null && termTime !== "") {
    grantCouponData.value.termBeginTime = termTime[0];
    grantCouponData.value.termEndTime = termTime[1];
  }
};

//发放优惠卷提交按钮
const submitGrantCoupon = async () => {
  timeFormSubmit(grantData.value.issueTime, grantData.value.termTime);
  const { code, message } = await IsCoupon(grantCouponData.value.id, grantCouponData.value);
  if (code === 200) {
    grantCoupon.value = false;
    ElMessage.success("发放优惠卷成功!");
    await fetchData();
  } else {
    ElMessage.error(message);
  }
};

//发放优惠卷数据模型
const grantCouponData = ref({
  id: "",
  issueBeginTime: "",//发放开始时间
  issueEndTime: "", // 发放结束时间
  termDays: 1, //有效天数
  termBeginTime: "", //使用有效期开始时间
  termEndTime: ""//使用有效期结束时间
});

const grantData = ref({
  way: 1, //发放方式
  issueTime: [], //发放时间数组
  usagePeriod: 1,  //使用期限方式
  termTime: [] //使用时间数组
});

//发放对话框是否可见
const grantCoupon = ref(false);

//发放按钮
const grant = (row) => {
  grantCoupon.value = true;
  grantCouponData.value.id = row.id;
  console.log(row);
};

//重置按钮
const resetData = () => {
  queryDto.value = {};
  fetchData();
};

//搜索按钮
const searchActivity = () => {
  fetchData();
};

//下拉框数据模型
const options = ref([{
  value: "zhinan",
  label: "指南"
}]);

// 定义分页查询方法
const fetchData = async () => {
  const { data } = await SelectCouponPage(queryDto.value);
  console.log(data);

  list.value = data.records;
  total.value = data.total;
};

// 定义搜索表单数据模型
const queryDto = ref({
  pageNum: 1,
  pageSize: 10,
  type: "",
  status: "",
  name: ""
});

const handleChange = (lastId, arr) => {
  couponAddDto.value.scopes = arr;
  console.log(arr);
};

// 添加表单对话框显示隐藏控制变量
const dialogVisible = ref(false);

//添加表单
const addShow = () => {
  dialogVisible.value = true;
};

// 表格数据模型
const list = ref([]);

// 分页条数据模型
const total = ref(0);


//添加表单数据模型
const couponAddDto = ref({
  name: "", //优惠券名称
  specific: false,//是否添限定使用范围，true：限定了，false：没限定
  scopes: [],//优惠券使用范围
  discountType: "每满减",//优惠券类型，1：每满减，2：折扣，3：无门槛，4：满减
  thresholdAmount: 0,//折扣门槛，0代表无门槛
  discountValue: 0, //折扣值，满减填抵扣金额；打折填折扣值：80标示打8折
  maxDiscountAmount: 0, //最大优惠金额
  totalNum: 0, //优惠券总量
  userLimit: 0, //每人领取的上限
  obtainWay: "手动领取" //获取方式1：手动领取，2：指定发放（通过兑换码兑换）
});

// 提交按钮事件处理函数
const submit = async () => {
  const { data, code, message } = await SaveCoupon(couponAddDto.value);
  if (code === 200) {
    dialogVisible.value = false;
    ElMessage.success("添加优惠卷成功!");
    await fetchData();
  } else {
    ElMessage.error(message);
  }
};


// onMounted钩子函数
onMounted(() => {
  fetchData();
});


</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 5px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

:deep(.el-form-item__label) {
  min-width: 100px;
}

.el_form_item_style {
  margin: 20px 20px;
}
</style>
